<template>
  <view class="body">
    <view class="top-info">
      <view class="amout">￥{{ amount / 100 }}/年</view>
      <img
        class="info-bg"
        src="https://ainengli.hzjrsw.com/jkhx/weight/lose-weight-manage.png"
        alt=""
      />
    </view>
    <img
      class="img-server1"
      src="https://ainengli.hzjrsw.com/jkhx/weight/server-info1.png"
      alt=""
    />
    <img
      class="img-server2"
      src="https://ainengli.hzjrsw.com/jkhx/weight/server-info2.png"
      alt=""
    />
    <view class="fixed">
      <view class="price">
        <text>￥</text>
        <text class="price-num">{{ amount / 100 }}</text>
        <text>/年</text>
      </view>
      <img
        @tap="buyMember"
        class="img-btn"
        src="https://ainengli.hzjrsw.com/jkhx/weight/vip-btn.png"
        alt=""
      />
    </view>
    <up-popup :show="isShow" :round="16" mode="bottom" closeable @close="isShow = false">
      <view class="title">请确认服务使用人</view>
      <view class="lists">
        <view class="item">
          <view class="info">
            <text class="name">{{ userInfo.patName }}</text>
            <text class="sex">{{ userInfo.gender }}</text>
            <text class="age">{{ userInfo.age }}岁</text>
          </view>
          <view v-if="userInfo && userInfo.relation !== null" class="relationShip">{{
            userInfo.relation
          }}</view>
        </view>
      </view>
      <view class="fixed" style="border: none">
        <button @tap="immediatelyPay" class="popup-btn">去支付</button>
      </view>
    </up-popup>
    <!-- <u-modal
      :show="isShow"
      @confirm="toQuestionnaire"
      @close="isShow = false"
      @cancel="isShow = false"
      :buttonReverse="true"
      :showCancelButton="true"
      title="提示"
      content="请您先填写个人信息，以便于我们了解您的当前状况。我们将根据您的情况为您制定更为合适的管理方案。"
      :closeOnClickOverlay="true"
    ></u-modal> -->
  </view>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue'
import { paying, getProduct, orderStatus } from '@/api/hmm'
import { onShow, onLoad, onUnload } from '@dcloudio/uni-app'
import { base_info } from '@/api/moreMessage'
import { subscribeMessage } from '@/api/index'
import store from '@/store'
const state = reactive({
  timeQuestions: null
})
const userInfo = ref({})
const userInfoNew = ref({})
const productObj = ref({})
const isShow = ref(false)
const bizOrderNo = ref('')

const amount = ref(0)
const isButtonDisabled = ref(false)
const isstop = ref(false)

onShow(() => {
  userInfo.value = uni.getStorageSync('userInfo')
    ? JSON.parse(uni.getStorageSync('userInfo')).patientInfo
    : {}
  userInfoNew.value = uni.getStorageSync('userInfo')
    ? JSON.parse(uni.getStorageSync('userInfo'))
    : {}
  init()
})
onUnload(() => {
  clearInterval(state.timeQuestions)
  state.timeQuestions = null
})
const init = () => {
  uni.showLoading({
    title: '加载中'
  })
  getProduct({ productId: 'P_WEIGHT_LOSE' }).then((res) => {
    if (isstop.value == false) {
      uni.hideLoading()
    }
    if (res.code == 0) {
      productObj.value = res.data
      amount.value = res.data && res.data.amount ? res.data.amount.toFixed(2) : 0
    }
  })
}
const buyMember = () => {
  if (!isButtonDisabled.value && !userInfo.value.questionState) {
    // 未填写问卷提示去填问卷
    uni.showModal({
      title: '提示',
      content:
        '请您先填写个人信息，以便于我们了解您的当前状况。我们将根据您的情况为您制定更为合适的管理方案。',
      confirmColor: '#00D1B6',
      success: (res) => {
        if (res.confirm) {
          toQuestionnaire()
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  } else {
    isShow.value = true
  }
}
const immediatelyPay = () => {
  const param = {
    productId: 'P_WEIGHT_LOSE',
    openId: userInfoNew.value.openId,
    channel: 'wechat_pay',
    method: 'jsapi',
    userId: userInfoNew.value.userId,
    phone: userInfoNew.value.phone,
    empi: userInfo.value.empi,
    patName: userInfo.value.patName
  }
  isButtonDisabled.value = true
  isShow.value = false
  uni.showLoading({
    title: '加载中'
  })
  setTimeout(() => {
    paying(param).then((res) => {
      uni.hideLoading()
      const payParam = JSON.parse(res.data.payBody)
      bizOrderNo.value = res.data.bizOrderNo
      uni.requestPayment({
        provider: 'wxpay',
        timeStamp: payParam.timeStamp,
        nonceStr: payParam.nonceStr,
        package: payParam.package,
        signType: payParam.signType,
        paySign: payParam.paySign,
        success: function (res) {
          isstop.value = true
          uni.showToast({
            title: '支付成功',
            icon: 'none',
            duration: 2000
          })
          // 点击按钮订阅消息
          const templat_id = 'oxk-aA4WH8sIHnY5kwTg4_QrFoQBX9H-tTqFUsWy_o4'
          uni.requestSubscribeMessage({
            tmplIds: [templat_id],
            success(res) {
              if (res.errMsg === 'requestSubscribeMessage:ok') {
                // 订阅成功，可以在这里触发订阅消息的后续操作
                pushMessage(res[templat_id])
              }
            },
            fail(err) {
              // 订阅失败，可以在这里处理订阅失败的情况
              uni.showToast({
                title: '消息订阅发送失败!',
                icon: 'error',
                duration: 2000
              })
            },
            complete(fis) {
              loopTime()
            }
          })
          //   console.log('success:' + JSON.stringify(res))
        },
        fail: function (err) {
          isstop.value = false
          isButtonDisabled.value = false
          // uni.showToast({
          //   title: '支付失败,请重试',
          //   icon: 'none',
          //   duration: 2000
          // })
          //   console.log('fail:' + JSON.stringify(err))
        }
      })
    })
  }, 200)
}
const loopTime = () => {
  let s = 0
  uni.showLoading({
    title: '加载中'
  })
  state.timeQuestions = setInterval(() => {
    s++
    if (s >= 2) {
      s = 0
      orderStatusFun()
    }
  }, 1000)
}
const orderStatusFun = () => {
  const param = bizOrderNo.value
  orderStatus(param).then((res) => {
    isstop.value = true
    if (res.data.payState == 'SUCCESS') {
      const params = {
        userId: userInfoNew.value.userId,
        empi: userInfo.value.empi
      }
      base_info(params).then((res) => {
        const info = Object.assign({}, JSON.parse(uni.getStorageSync('userInfo')))
        info.patientInfo = res.data
        store.commit('SET_USERINFO', info)
        clearInterval(state.timeQuestions)
        state.timeQuestions = null
        // setTimeout(() => {
        isstop.value = false
        isButtonDisabled.value = false
        uni.navigateBack({
          delta: 1
        })
        // }, 2000)
      })
    } else {
      clearInterval(state.timeQuestions)
      state.timeQuestions = null
    }
  })
}

const pushMessage = (status: string) => {
  // 订阅成功提醒后端
  const params = {
    tempId: 'oxk-aA4WH8sIHnY5kwTg4_QrFoQBX9H-tTqFUsWy_o4',
    openId: userInfoNew.value.openId,
    empi: userInfo.value.empi,
    state: status,
    bizNo: bizOrderNo.value
  }
  subscribeMessage(params).then((res) => {
    console.log('订阅成功推送', params, res)
  })
}

const toQuestionnaire = () => {
  uni.redirectTo({ url: '/packA/pages/weightManage/questionnaire' })
}
</script>

<style lang="scss" scoped>
.body {
  position: relative;
  height: 100%;
  padding-bottom: calc(224rpx + constant(safe-area-inset-bottom));
  padding-bottom: calc(224rpx + env(safe-area-inset-bottom));
  background: #fff9ee;

  .img-Bg {
    position: absolute;
    top: 0;
    left: 0;
    z-index: -1;
    width: 100%;
    height: 655rpx;
  }

  .top-info {
    position: relative;

    .info-bg {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 345rpx;
      // box-shadow: 0 8rpx 12rpx 0 rgba(201, 173, 134, 0.28)
    }

    .amout {
      position: absolute;
      top: 118rpx;
      right: 68rpx;
      z-index: 2;
      display: inline-block;
      padding: 12rpx 24rpx;
      font-size: 28rpx;
      font-weight: 700;
      color: #fff7e7;
      background: linear-gradient(95deg, #ff9a2d 0%, #ff4d00 100%),
        linear-gradient(317deg, #ff4900 0%, #ff7431 100%);
      border-radius: 40rpx;
    }
  }

  .img-server1 {
    width: 100%;
    height: 686rpx;
    margin-top: 352rpx;
  }

  .img-server2 {
    width: 100%;
    height: 1910rpx;
  }

  .fixed {
    position: fixed;
    bottom: 0;
    left: 0;
    z-index: 10;
    box-sizing: border-box;
    display: flex;
    gap: 24rpx;
    justify-content: space-between;
    width: 100%;
    padding: 24rpx 32rpx;
    padding-bottom: calc(24rpx + constant(safe-area-inset-bottom));
    padding-bottom: calc(24rpx + env(safe-area-inset-bottom));
    background: #fff;

    .popup-btn {
      width: 100%;
      font-size: 32rpx;
      font-weight: 500;
      color: #fff;
      background: linear-gradient(95deg, #ff9a2d 0%, #ff4d00 100%), #00d1b6;
      border-radius: 44rpx;
    }

    .img-btn {
      position: absolute;
      top: 32rpx;
      left: 32rpx;
      width: calc(100vw - 64rpx);
      height: 108rpx;
    }

    .price {
      position: relative;
      z-index: 2;
      display: flex;
      align-items: baseline;
      height: 108rpx;
      padding-left: 50rpx;
      font-size: 28rpx;
      font-weight: 400;
      line-height: 108rpx;
      color: #feedcd;

      .price-num {
        font-size: 48rpx;
        font-weight: 700;
      }
    }
  }

  .u-popup {
    .title {
      height: 108rpx;
      font-size: 32rpx;
      font-weight: 500;
      line-height: 108rpx;
      color: #222;
      text-align: center;
      border-bottom: 1rpx solid #e5e6eb;
    }

    .lists {
      padding: 32rpx;
      padding-bottom: calc(108rpx + constant(safe-area-inset-bottom));
      padding-bottom: calc(108rpx + env(safe-area-inset-bottom));

      .item {
        box-sizing: border-box;
        display: flex;
        align-items: center;
        justify-content: space-between;
        height: 96rpx;
        padding: 0 32rpx;
        margin-bottom: 24rpx;
        font-size: 30rpx;
        font-weight: 400;
        color: #666;
        background: #fafafa;
        border-radius: 8rpx;

        .info {
          display: flex;
          gap: 24rpx;
          align-items: center;
          justify-content: space-between;
        }

        .name {
          font-size: 36rpx;
          font-weight: 500;
          color: #222;
        }

        .relationShip {
          width: 96rpx;
          height: 40rpx;
          font-size: 24rpx;
          font-weight: 400;
          line-height: 40rpx;
          color: #fff;
          text-align: center;
          background: #00d1b6;
          border-radius: 20rpx;
        }
      }

      .item:last-child {
        margin-bottom: 0;
      }
    }
  }
}
</style>
